package com.quyl.poi.run;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quyl.poi.model.BaseInfo;
import com.quyl.poi.service.PoiExcelService;
import com.quyl.poi.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 程序执行
 */
@Slf4j
@Component
public class ExcelToHtmlRunner implements CommandLineRunner {
    @Resource
    private PoiExcelService poiExcelService;
    @Resource
    private TemplateEngine templateEngine;

    private static String finalFileContentPath = null;


    @Override
    public void run(String... args) throws Exception {
        String path = Constant.DEFAULT_PATH;
        if (args.length > 0 && StrUtil.isNotEmpty(args[0])) {
            path = args[0];
        }
        log.info("文件路径为:{}", path);
        List<Map<String, Object>> mapList = poiExcelService.callableTask(path);
        if (CollectionUtil.isEmpty(mapList)) {
            return;
        }
        String replace = null;
        String operateSystem = CommonUtils.getOperateSystem();

        JSONArray jsonArray = JSON.parseArray(JSONUtil.toJsonStr(mapList));
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject excelData = (JSONObject) jsonArray.get(i);
            //获取主题和模型分层，建立目录结构
            String baseInfo = excelData.get(Constant.BASIC_INFO).toString();
            List<BaseInfo> baseInfoList = JSON.parseArray(baseInfo).toJavaList(BaseInfo.class);
            //主题名
            String topicName = baseInfoList.stream().filter(x -> x.getKey().equals("主题")).collect(Collectors.toList()).get(0).getValue()+i;
            //获取子主题
            String chirldTopicName = baseInfoList.stream().filter(x -> x.getKey().equals("子主题")).collect(Collectors.toList()).get(0).getValue()+i;
            //合并成为新的主题
            String newTopicName;
            if (chirldTopicName != null && !chirldTopicName.equals("")) {
                newTopicName = topicName + ">" + chirldTopicName;
            } else {
                newTopicName = topicName;
            }
            log.debug("当前合并处理后的新主题是：" + newTopicName);
            //模型分层
            String modelName = baseInfoList.stream().filter(x -> x.getKey().equals("模型分层")).collect(Collectors.toList()).get(0).getValue()+i;
            if (newTopicName != null && !newTopicName.equals("")) {
                replace = newTopicName.replace(">", Constant.SEPARATOR);
            }
            //获取主题生成对应的文件夹目录
            finalFileContentPath = operateSystem + Constant.ROOT + Constant.SEPARATOR + modelName + Constant.SEPARATOR + replace + Constant.SEPARATOR;
            log.debug("获取主题生成对应的文件夹目录：" + finalFileContentPath);
            //获取生成文件的名字
            String tableName = excelData.get(Constant.TABLE_NAME).toString()+i;
            String fileName = tableName + Constant.SUFFIX;
            File fp = new File(finalFileContentPath);
            // 判断目录是否存在，如果不存在则建立
            if (!fp.exists()) {
                // 目录不存在的情况下，创建目录。
                fp.mkdirs();
            }
            //复制css样式，讲样式放在顶层
            String cssStylePath = operateSystem + Constant.ROOT + Constant.SEPARATOR;
            CssUtil.copyCssStyle(cssStylePath);
            //赋值操作
            Context context = SetDataUtil.copyValueForHtml(cssStylePath, excelData);

            //读取html文件，并动态赋值
            String htmlContent = templateEngine.process("model", context);
            HtmlUtil.setHtml(htmlContent, finalFileContentPath, fileName);
            log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
            log.debug("   _____ _    _  _____ _____ ______  _____ _____ \n\n\n\n" + "  / ____| |  | |/ ____/ ____|  ____|/ ____/ ____|\n" + " | (___ | |  | | |   | |    | |__  | (___| (___  \n" + "  \\___ \\| |  | | |   | |    |  __|  \\___ \\\\___ \\ \n" + "  ____) | |__| | |___| |____| |____ ____) |___) |\n" + " |_____/ \\____/ \\_____\\_____|______|_____/_____/ \n" + "                                                 \n" + "                                                 ");
            log.debug("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        }
    }
}
